package com.e3roid.examples;

import android.view.MotionEvent;

import com.e3roid.E3Activity;
import com.e3roid.E3Engine;
import com.e3roid.E3Scene;
import com.e3roid.drawable.Background;
import com.e3roid.drawable.Sprite;
import com.e3roid.drawable.texture.AssetTexture;
import com.e3roid.drawable.texture.Texture;
import com.e3roid.drawable.texture.TiledTexture;
import com.e3roid.opengl.RenderSurfaceView;

public class XMLLayoutExample extends E3Activity {

	private final static int WIDTH  = 240;
	private final static int HEIGHT = 240;
	
	private Texture robotTexture;
	private Sprite robot;

	@Override
	protected void onSetContentView() {
		this.setContentView(R.layout.xmllayout);
		this.surfaceView = (RenderSurfaceView)this.findViewById(R.id.xmllayout_view);
		this.surfaceView.setRenderer(this.engine);		
	}
	
	@Override
	public E3Engine onLoadEngine() {
		E3Engine engine = new E3Engine(this, WIDTH, HEIGHT, E3Engine.RESOLUTION_FIXED_RATIO);
		engine.requestFullScreen();
		engine.requestPortrait();
		return engine;
	}

	@Override
	public E3Scene onLoadScene() {
		E3Scene scene = new E3Scene();
		scene.addEventListener(this);
		
		int centerX = (getWidth()  - robotTexture.getWidth())  / 2;
		int centerY = (getHeight() - robotTexture.getHeight()) / 2;
		
		robot = new Sprite(robotTexture, centerX, centerY);
		scene.getTopLayer().add(robot);
		
		Background background = new Background(
				new TiledTexture("background.png", getWidth(), getHeight(), this));
		scene.getTopLayer().setBackground(background);
		
		return scene;
	}

	@Override
	public void onLoadResources() {
		robotTexture = new AssetTexture("robot.png", this);
	}
	
	@Override
	public boolean onSceneTouchEvent(E3Scene scene, MotionEvent motionEvent) {
		if (robot != null) {
			if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
				// x and y must be adjusted to scene's screen position because
				// MotionEvent's getX()&getY() returns pixel position of the actual device.
				int x = getTouchEventX(scene, motionEvent);
				int y = getTouchEventY(scene, motionEvent);
				// Because x and y can be negative or can be out of the view
				// when using with layout container, x and y values must be checked.
				if (x >= 0 && y >=0 && x <= getWidth() && y <= getHeight()) {
					x -= robotTexture.getWidth()  / 2;
					y -= robotTexture.getHeight() / 2;
					robot.move(x, y);
				}
			}
		}
		return false;
	}
}
